//
//  SASaleDocumentsDetailVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/10.
//

#import "SASaleDocumentsDetailVC.h"
#import "SASalesInvoiceDetailAPI.h"
#import "SASalesInvoiceDetailModel.h"
#import "SASaleDocumentsHeaderView.h"
#import "SASaleDocumentsDetailCell.h"
#import "SAPrintReceiptSell.h"
#import "SACloudPrintPushPrintMsgAPI.h"
#import "SASalesSalesPayAPI.h"
#import "SAReceiveQueryStatusAPI.h"
#import "ScanHelper.h"
#import "GFAlertView.h"
#import "YBImageBrowser.h"
#import "SAQueryPrinterStatusAPI.h"
#import "SAPrintTicketAPI.h"

@interface SASaleDocumentsDetailVC ()<HTTPAPIDelegate, UITableViewDelegate, UITableViewDataSource,YBImageBrowserDataSource>

@property (nonatomic, strong) NSString *saleOrderId;
@property (nonatomic, strong) NSString *saleOrderNo;

@property (nonatomic, strong) UILabel *memberLab;
@property (nonatomic, strong) UILabel *storeNameLab;
@property (nonatomic, strong) UILabel *moneyLab;
@property (nonatomic, strong) UILabel *saleDateLab;
@property (nonatomic, strong) UILabel *dateLab;
@property (nonatomic, strong) UILabel *payTypeLab;
@property (nonatomic, strong) UILabel *orderTypeLab;
@property (nonatomic, strong) UILabel *remarkLab;

@property (nonatomic, strong) SASalesInvoiceDetailAPI *salesInvoiceDetailAPI;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SASalesInvoiceDetailModel *salesInvoiceDetailModel;
@property (nonatomic, strong) UILabel *footTitleLab;
@property (nonatomic, strong) UIButton *printBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) SACloudPrintPushPrintMsgAPI *cloudPrintPushPrintMsgAPI;
@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) UIButton *payBtn;

@property (nonatomic, strong) NSString *salesOrderId;
@property (nonatomic, strong) NSString *salesOrderNo;
@property (nonatomic, strong) SASalesSalesPayAPI *salesSalesPayAPI;
@property (nonatomic, strong) SAReceiveQueryStatusAPI *receiveQueryStatusAPI;

@property (nonatomic, assign) BOOL isPolling;
@property (nonatomic, strong) NSTimer *timer2;
@property (nonatomic, assign) int count2;
@property (nonatomic, strong) UIView *grayView2;//标题头
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) NSString *merchantId;

@property (nonatomic, strong) SAQueryPrinterStatusAPI *queryPrinterStatusAPI;
@property (nonatomic, strong) SAPrintTicketAPI *printTicketAPI;

@end

@implementation SASaleDocumentsDetailVC

-(instancetype)initWithSaleOrderId:(NSString *)saleOrderId AndSaleOrderNo:(NSString *)saleOrderNo MerchantId:(NSString *)merchantId {
    if (self = [super init]) {
        self.saleOrderId = saleOrderId;
        self.saleOrderNo = saleOrderNo;
        self.merchantId = merchantId;
        self.overallSetting = [SAOverallSetting shareInstance];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.salesInvoiceDetailAPI == api) {
        self.salesInvoiceDetailModel = [SASalesInvoiceDetailModel mj_objectWithKeyValues:data[@"data"]];
        if (self.salesInvoiceDetailModel.memberName.length > 0) {
            self.memberLab.text = [NSString stringWithFormat:@"%@(%@)",self.salesInvoiceDetailModel.memberName,self.salesInvoiceDetailModel.mobile];
        }else {
            self.memberLab.text = @"散客";
        }
        self.storeNameLab.text = [NSString stringWithFormat:@"%@(%@)",self.salesInvoiceDetailModel.empName,self.salesInvoiceDetailModel.empMobile];
        self.moneyLab.text = [NSString stringWithFormat:@"%0.2f",[self.salesInvoiceDetailModel.actualPrice floatValue] / 100.f];
        self.saleDateLab.text = self.salesInvoiceDetailModel.salesTime;
        self.dateLab.text = self.salesInvoiceDetailModel.createTime;
        self.remarkLab.text = self.salesInvoiceDetailModel.remark;
        self.footTitleLab.text = self.salesInvoiceDetailModel.formula;
        
        NSMutableArray *payMarr = [NSMutableArray array];
        for (SASalePayListModel *list in self.salesInvoiceDetailModel.payList) {
            if ([list.payType isEqualToString:@"1"]) {
                NSString *str = [NSString stringWithFormat:@"现金(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"2"]) {
                NSString *str = [NSString stringWithFormat:@"刷卡(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"4"]) {
                NSString *str = [NSString stringWithFormat:@"微信(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"5"]) {
                NSString *str = [NSString stringWithFormat:@"支付宝(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"6"]) {
                NSString *str = [NSString stringWithFormat:@"余额(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"7"]) {
                NSString *str = [NSString stringWithFormat:@"扫码收款(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }
        }
        self.payTypeLab.text = [payMarr componentsJoinedByString:@" "];
        
        BOOL isPay = YES;
        BOOL isPrint = YES;
        self.footTitleLab.frame = CGRectMake(0, kScreenHeight - kScaleNum(58) - SafeFooterHeight, kScreenWidth, kScaleNum(22));
        switch (self.salesInvoiceDetailModel.status) {
            case 0:
                isPay = NO;
                self.orderTypeLab.text = @"待支付";
                break;
            case 2:
                isPrint = NO;
                self.orderTypeLab.text = @"已支付";
                break;
            case 4:
                self.orderTypeLab.text = @"已取消";
                break;
            case 6:
                self.orderTypeLab.text = @"部分退";
                isPrint = NO;
                break;
            case 8:
                self.orderTypeLab.text = @"已退款";
                isPrint = NO;
                break;
            default:
                self.orderTypeLab.text = @"";
                break;
        }
        
        [self.tableView reloadData];
        if (self.salesInvoiceDetailModel.merchantId != [SAValueManger shareInStance].userInfo.merchantId) {
            isPay = YES;
        }
        self.salesOrderId = self.salesInvoiceDetailModel.saleOrderId;
        self.salesOrderNo = self.salesInvoiceDetailModel.saleOrderNo;
        self.payBtn.hidden = isPay;
        self.printBtn.hidden = isPrint;
        if (isPay == YES && isPrint == YES) {
            self.footTitleLab.frame = CGRectMake(0, kScreenHeight - kScaleNum(22) - SafeFooterHeight, kScreenWidth, kScaleNum(22));
        }
    }else if (self.cloudPrintPushPrintMsgAPI == api) {
        [Prompt popPromptViewWithMsg:@"正在进行共享打印" duration:2];
    }else if (self.salesSalesPayAPI == api) {
        NSInteger status = [data[@"status"] integerValue];
        if (status == 2) {
            self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
            [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
            [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
            [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
        }else if (status == 0) {
            self.isPolling = YES;
            self.count2 = 31;
            [HDHubView loadingMessage:@"正在查询支付状态..."];
            self.receiveQueryStatusAPI.orderNo = self.salesOrderNo;
            self.timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired2) userInfo:nil repeats:YES];
        }else {
            [self tipAlertView:@"支付失败"];
        }
    }else if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            NSInteger status = [data[@"data"][@"status"] integerValue];
            if (status == 2) {
                self.isPolling = NO;
                [self.timer2 invalidate];
                self.timer2 = nil;
                [HDHubView dismissLoading];
                self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
                [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
                [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
                [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
            }else if (status == 6 || status == 8) {
                self.isPolling = NO;
                [self.timer2 invalidate];
                self.timer2 = nil;
                [HDHubView dismissLoading];
                [self tipAlertView:@"支付失败"];
            }
        }
    }else if (self.queryPrinterStatusAPI == api) {
        NSString *status = data[@"data"][@"status"];
        NSString *type = data[@"data"][@"type"];
        if ([status isEqualToString:@"1"] && [type isEqualToString:@"1"]) {
            self.printTicketAPI.ticketType = @"1";
            self.printTicketAPI.salesOrderId = self.salesInvoiceDetailModel.saleOrderId;
            [self.printTicketAPI submitForm:POST];
        }else {
            if (kIsTestServer == 1) {
                self.cloudPrintPushPrintMsgAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
                self.cloudPrintPushPrintMsgAPI.type = @"1";
                self.cloudPrintPushPrintMsgAPI.data = self.salesInvoiceDetailModel.saleOrderId;
                [self.cloudPrintPushPrintMsgAPI submitForm:POST];
            }else {
                [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
            }
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            self.isPolling = NO;
            [self.timer2 invalidate];
            self.timer2 = nil;
            [HDHubView dismissLoading];
            NSDictionary *dic = error.userInfo;
            NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [self tipAlertView:msg];
        }
    }else if (self.salesSalesPayAPI == api) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        [self tipAlertView:msg];
    }else if (self.queryPrinterStatusAPI == api) {
        if (kIsTestServer == 1) {
            self.cloudPrintPushPrintMsgAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
            self.cloudPrintPushPrintMsgAPI.type = @"1";
            self.cloudPrintPushPrintMsgAPI.data = self.salesInvoiceDetailModel.saleOrderId;
            [self.cloudPrintPushPrintMsgAPI submitForm:POST];
        }else {
            [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
        }
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.salesInvoiceDetailModel.productList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.salesInvoiceDetailModel.productList[section].skuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASaleDocumentsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASaleDocumentsDetailCell" forIndexPath:indexPath];
    SASaleSkuListModel *model = self.salesInvoiceDetailModel.productList[indexPath.section].skuList[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SASaleDocumentsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SASaleDocumentsHeaderView"];
    SAProductListModel *model = self.salesInvoiceDetailModel.productList[section];
    header.model = model;
    WeakSelf
    header.imageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

-(void)clickedPrintBtn {
    [self startTime];
    if (self.overallSetting.printerSetting.printerStatus == 2 && [SAValueManger shareInStance].printType == 1) {
        [SAPrintReceiptSell printWithTotalData:self.salesInvoiceDetailModel printSuccessBlock:^{
            
        }];
    }else {
        [self.queryPrinterStatusAPI submitForm:POST];
    }
}

-(void)clickedPayBtn {
    [self scanQrcode];
}

-(void)startTime {
    self.printBtn.userInteractionEnabled = NO;
    [self.printBtn setTitle:@"打印" forState:UIControlStateNormal];
    self.count = 3;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
    } else {
        self.printBtn.userInteractionEnabled = YES;
        [self.printBtn setTitle:@"打印" forState:UIControlStateNormal];
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)scanQrcode {
    WeakSelf
    __block NSString *salesOrderId = self.salesOrderId;
    __block NSString *salesOrderNo = self.salesOrderNo;
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:weixinStyle qrResultCallBack:^(id result) {
        weakSelf.salesSalesPayAPI.authCode = result;
        weakSelf.salesSalesPayAPI.salesOrderId = salesOrderId;
        weakSelf.salesSalesPayAPI.salesOrderNo = salesOrderNo;
        [weakSelf.salesSalesPayAPI sendRequestToServerWithActivityViewAndMask:POST];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

- (void)timerFired2 {
    if (self.count2 != 1) {
        self.count2 -= 1;
        [self.receiveQueryStatusAPI sendRequestToServerWithType:POST];
    } else {
        self.isPolling = NO;
        // 停掉定时器
        [self.timer2 invalidate];
        self.timer2 = nil;
        [HDHubView dismissLoading];
    }
}

-(void)tipAlertView:(NSString *)msg {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:msg knowBtnBlock:^(UIButton *knowBtn) {
        [knowBtn setTitle:@"重试" forState:UIControlStateNormal];
        [knowBtn addTarget:self action:@selector(continuePay) forControlEvents:UIControlEventTouchUpInside];
    }];
    [alertView showWithAnimation];
}

-(void)continuePay {
    [self scanQrcode];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    self.grayView2.hidden = y < kScaleNum(261);
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:self.saleOrderNo];
    [self setBgImage:nil];
    
    UIView *headerView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 296)];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerView];
    
    NSArray *arr = @[@"实收金额", @"会员", @"店员", @"支付方式", @"订单状态", @"销售日期", @"创建时间", @"备注"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(51 + 30 * (i - 1)), kScaleNum(70), kScaleNum(30))];
        titleLab.text = arr[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kLightgGrayColor;
        [headerView addSubview:titleLab];
        
        UILabel *contentLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(285), kScaleNum(51 + 30 * (i - 1)), kScaleNum(265), kScaleNum(30))];
        contentLab.font = kFont(15);
        contentLab.textAlignment = NSTextAlignmentRight;
        contentLab.textColor = kLightgGrayColor;
        [headerView addSubview:contentLab];
        
        if (i == 0) {
            self.moneyLab = contentLab;
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(100), kScaleNum(50));
            contentLab.frame = CGRectMake(kScreenWidth - kScaleNum(255), 0, kScaleNum(235), kScaleNum(50));
            titleLab.font = kFont(18);
            contentLab.font = kFont(18);
            titleLab.textColor = kBlackColor;
            contentLab.textColor = kBlackColor;
        }else if (i == 1) {
            self.memberLab = contentLab;
        }else if (i == 2) {
            self.storeNameLab = contentLab;
        }else if (i == 3) {
            self.payTypeLab = contentLab;
        }else if (i == 4) {
            self.orderTypeLab = contentLab;
        }else if (i == 5) {
            self.saleDateLab = contentLab;
        }else if (i == 6) {
            self.dateLab = contentLab;
        }else if (i == 7) {
            self.remarkLab = contentLab;
        }

        if (i == 0) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(50), kScreenWidth - kScaleNum(40), kScaleNum(1))];
            line.backgroundColor = kLineColor;
            [headerView addSubview:line];
        }
    }
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(261), kScreenWidth, kScaleNum(35))];
    grayView.backgroundColor = kColor(228, 231, 243, 1);
    [headerView addSubview:grayView];
    NSArray *arr2 = @[@"商品", @"数量", @"单价", @"小计", @"折后额"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kLightgGrayColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(101), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(179), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(236), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 4) {
            titleLab.frame = CGRectMake(kScaleNum(296), 0, kScaleNum(78), kScaleNum(35));
        }
    }
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = headerView;
    
    UILabel *footTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(58) - SafeFooterHeight, kScreenWidth, kScaleNum(22))];
    footTitleLab.font = kFont(12);
    footTitleLab.backgroundColor = kBgColor;
    footTitleLab.textColor = kLightgGrayColor;
    footTitleLab.textAlignment = NSTextAlignmentRight;
    self.footTitleLab = footTitleLab;
    [self.view addSubview:self.footTitleLab];
    
    self.salesInvoiceDetailAPI.salesOrderId = self.saleOrderId;
    self.salesInvoiceDetailAPI.merchantId = self.merchantId;
    [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    UIButton *payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    payBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth, kScaleNum(35) + SafeFooterHeight);
    payBtn.backgroundColor = kPinkColor;
    [payBtn setTitle:@"去支付" forState:UIControlStateNormal];
    payBtn.titleLabel.font = kBFont(18);
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payBtn addTarget:self action:@selector(clickedPayBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:payBtn];
    payBtn.hidden = YES;
    self.payBtn = payBtn;
    
    UIButton *printBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    printBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth, kScaleNum(35) + SafeFooterHeight);
    [printBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
    [printBtn setTitle:@"打印" forState:UIControlStateNormal];
    printBtn.titleLabel.font = kBFont(18);
    [printBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [printBtn addTarget:self action:@selector(clickedPrintBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:printBtn];
    printBtn.hidden = YES;
    self.printBtn = printBtn;
    
    UIView *grayView2 = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight)-0.5, kScreenWidth, kScaleNum(35))];
    grayView2.backgroundColor = kColor(228, 231, 243, 1);
    grayView2.hidden = YES;
    [self.view addSubview:grayView2];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kLightgGrayColor;
        [grayView2 addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(101), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(179), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(236), 0, kScaleNum(65), kScaleNum(35));
        }else if (i == 4) {
            titleLab.frame = CGRectMake(kScaleNum(296), 0, kScaleNum(78), kScaleNum(35));
        }
    }
    self.grayView2 = grayView2;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 57) - SafeFooterHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsHeaderView class] forHeaderFooterViewReuseIdentifier:@"SASaleDocumentsHeaderView"];
        [_tableView registerClass:[SASaleDocumentsDetailCell class] forCellReuseIdentifier:@"SASaleDocumentsDetailCell"];
    }
    return _tableView;
}

-(SASalesInvoiceDetailAPI *)salesInvoiceDetailAPI {
    if (!_salesInvoiceDetailAPI) {
        _salesInvoiceDetailAPI = [SASalesInvoiceDetailAPI apiWithDelegate:self];
    }
    return _salesInvoiceDetailAPI;
}

-(SACloudPrintPushPrintMsgAPI *)cloudPrintPushPrintMsgAPI {
    if (!_cloudPrintPushPrintMsgAPI) {
        _cloudPrintPushPrintMsgAPI = [SACloudPrintPushPrintMsgAPI apiWithDelegate:self];
    }
    return _cloudPrintPushPrintMsgAPI;
}

-(SASalesSalesPayAPI *)salesSalesPayAPI {
    if (!_salesSalesPayAPI) {
        _salesSalesPayAPI = [SASalesSalesPayAPI apiWithDelegate:self];
        _salesSalesPayAPI.isPromptErrorMessage = NO;
    }
    return _salesSalesPayAPI;
}

-(SAReceiveQueryStatusAPI *)receiveQueryStatusAPI {
    if (!_receiveQueryStatusAPI) {
        _receiveQueryStatusAPI = [SAReceiveQueryStatusAPI apiWithDelegate:self];
        _receiveQueryStatusAPI.isPromptErrorMessage = NO;
    }
    return _receiveQueryStatusAPI;
}

-(SAQueryPrinterStatusAPI *)queryPrinterStatusAPI {
    if (!_queryPrinterStatusAPI) {
        _queryPrinterStatusAPI = [SAQueryPrinterStatusAPI apiWithDelegate:self];
    }
    return _queryPrinterStatusAPI;
}

-(SAPrintTicketAPI *)printTicketAPI {
    if (!_printTicketAPI) {
        _printTicketAPI = [SAPrintTicketAPI apiWithDelegate:self];
    }
    return _printTicketAPI;
}

@end
